﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Cfg;

namespace METODESA.Server.Data.METODESA.Nhibernate
{

    public static class NHibernateHelper
    {
        #region NHibernateHelperAttributes

        
        private static ISessionFactory mySessionFactory;
        private static ISession myCurrentSession;
        private static Configuration myConfiguration;

        #endregion

        /// <summary>
        /// Creates an NHibernate ISessionFactory with the specified configuration in web.config
        /// </summary>
        static NHibernateHelper()
        {
            try
            {
                myConfiguration = new Configuration();
                //TODO cambiar la ruta a una dinamica
                 myConfiguration.Configure("c:\\hibernate.cfg.xml");
                mySessionFactory = myConfiguration.BuildSessionFactory();
            }
            catch (Exception error)
            {
                Console.Out.WriteLine(error.Message);
            }
        }

        /// <summary>
        /// Method that creates an ISession from the ISession factory if was not created
        /// early, otherwise it returns the current ISession
        /// </summary>
        /// <returns>Return the current ISession</returns>
        public static ISession GetCurrentSession()
        {
            if (myCurrentSession == null)
            {
             
                myCurrentSession = mySessionFactory.OpenSession();

            }
            return myCurrentSession;
        }

        /// <summary>
        /// Method to close the current ISession
        /// </summary>
        public static void CloseSession()
        {
            if (myCurrentSession == null)
                return;

            myCurrentSession.Close();
        }

        /// <summary>
        /// Method to close the ISessionFactory
        /// </summary>
        public static void CloseSessionFactory()
        {
            if (mySessionFactory != null)
                mySessionFactory.Close();
        }
    }
}
